package trip_passenger

import (
	"database/sql"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/app"
	"sweetsunnyflower/pkg/database"
	"sweetsunnyflower/pkg/paginator"

	"github.com/gin-gonic/gin"
	"github.com/golang-module/carbon/v2"
)

func Get(idstr string) (tripPassenger TripPassenger) {
	database.DB.Where("id", idstr).First(&tripPassenger)
	return
}

func GetBy(field, value string) (tripPassenger TripPassenger) {
	database.DB.Where("? = ?", field, value).First(&tripPassenger)
	return
}

func All() (tripPassengers []TripPassenger) {
	database.DB.Find(&tripPassengers)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(TripPassenger{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

func Paginate(c *gin.Context, perPage int) (tripPassengers []TripPassenger, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(TripPassenger{}),
		&tripPassengers,
		app.V1URL(database.TableName(&TripPassenger{})),
		perPage,
	)
	return
}

func GetLatestByUserID(userID uint64) (tripPassenger TripPassenger) {
	database.DB.Where("user_id", userID).Order("id desc").First(&tripPassenger)
	return
}

func GetByTripIdAndUserID(userID uint64, tripID uint64) (tripPassenger TripPassenger) {
	database.DB.Where("user_id", userID).Where("trip_id", tripID).Order("id desc").First(&tripPassenger)
	return
}

// 预定座位总数
func SumBooking(tripID uint64) (SumBooking int64, err error) {
	model := database.DB.Model(&TripPassenger{})

	var sum sql.NullInt64

	if err := model.Where("trip_id = ?", tripID).Where("status = ?", CONFIRMED).Select("sum(booking) as sum").Find(&sum).Error; err != nil {
		return 0, err
	}

	if sum.Valid {
		SumBooking = sum.Int64
	}

	return SumBooking, nil
}

func GetPassengersByTripID(tripID uint64) (passengers []TripPassenger, err error) {
	err = database.DB.Where("trip_id", tripID).Find(&passengers).Error
	return passengers, err
}

func GetByLatestId(query requests.TripPassengersQueryRequest) (tripPassenger []TripPassenger) {

	model := database.DB

	if query.UserID > 0 {
		model = model.Where("user_id = ?", query.UserID)
	}

	if query.Status > 0 {
		model = model.Where("status = ?", query.Status)
	}

	if query.LatestId > 0 {
		model = model.Where("id < ?", query.LatestId)
	}

	if query.Time != "" {
		model = model.Where("time >= ?", query.Time).Where("time < ?", carbon.Parse(query.Time).AddDay().ToDateTimeString())
	}

	model.Order("id desc").Limit(query.Limit).Find(&tripPassenger)

	return
}
